package com.kyzh.core.activities

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.gushenge.atools.util.setHeight
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Pinglun
import com.gushenge.core.dao.MMKVConsts.gid
import com.gushenge.core.impls.GameImpl
import com.kyzh.core.R
import com.kyzh.core.adapters.GameDetailBannerAdapter
import com.kyzh.core.databinding.ItemDynamicDiscuss1Binding
import com.kyzh.core.dialog.showDynamicDiscussAddDialog
import com.kyzh.core.dialog.showSendMessageDialog
import com.kyzh.core.utils.reviewImages
import com.kyzh.core.utils.setVisibility
import com.kyzh.core.utils.startLogin
import com.littlejerk.rvdivider.builder.XGridBuilder
import com.shuyu.gsyvideoplayer.GSYVideoManager
import kotlinx.android.synthetic.main.activity_comment_detail.*
import kotlinx.android.synthetic.main.activity_comment_detail.rbStar
import kotlinx.android.synthetic.main.activity_comment_detail.tvContent
import kotlinx.android.synthetic.main.activity_comment_detail.tvName
import kotlinx.android.synthetic.main.activity_comment_detail.tvTime
import kotlinx.android.synthetic.main.item_video_discuss.*
import org.jetbrains.anko.dip

class CommentDetailActivity : BaseActivity() {
    companion object{
        @JvmStatic
        fun start(context: Context,pinglun : Pinglun?) {
            val starter = Intent(context, CommentDetailActivity::class.java)
                .putExtra("pinglun",pinglun)
            context.startActivity(starter)
        }
    }
    private var id:String = ""
    private var pid:String = ""
    private var ppid:String = ""
    private lateinit var  pinglunAdapter : PinglunAdapter
    private var pinglun2: Pinglun? =null

    private var list:ArrayList<Pinglun> = arrayListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_comment_detail)

        initView()
        initData()
    }

    fun initView(){

        pinglun2= intent.getSerializableExtra("pinglun") as Pinglun
        close.setOnClickListener {
            finish()
        }
        tvDiscuss.setOnClickListener {

            if(startLogin()){
                showSendMessageDialog {
                    GameImpl.pushPingLun(this@CommentDetailActivity,gid,null,null,this,"",pinglun2!!.id,pinglun2!!.id,2,null){
                        if(this){
                            initData()
                        }
                    }
                }
            }

        }
        pinglun2?.apply {
            tvSubmit.hint = "回复：${pinglun2!!.user_name}"
            tvTitle.text = "${num}条回复"
            Glide.with(this@CommentDetailActivity).load(touxiang).into(ivHead)
            Glide.with(this@CommentDetailActivity).load(head_frame).into(ivHeadF)
            Glide.with(this@CommentDetailActivity).load(medal).into(imgMedal)
            Glide.with(this@CommentDetailActivity).load(huiyuan_img).into(imgVip)
            if(color.isNullOrEmpty()){
                tvName.setTextSize(14f)
                tvName .setHasColors(false,null)
                tvName.setText(user_name)
            }else{
                if(color.size == 1){
                    tvName.setTextSize(14f)
                    tvName.setText(user_name)
                    tvName .setHasColors(false,null)
                    tvName.setTextColor(Color.parseColor(color[0]))
                }else{
                    var intArray = IntArray(color!!.size)
                    color?.forEachIndexed { index, s ->
                        intArray[index] = Color.parseColor(s)
                    }

                    tvName.setTextSize(14f)
                    tvName.setTextColor(Color.parseColor(color[0]))
                    tvName.setText(user_name)
                    tvName .setHasColors(true,intArray)

                }
            }
            if(!point.isNullOrEmpty()){
                rbStar.rating = point.toFloat()
            }
            tvContent.text = content
            tvTime.text = time
            tv_pinglun.text = num.toString()
            tv_dianzan.text = zan
            if(images.isNullOrEmpty()&&video.isNullOrEmpty()){
                rvList2.setVisibility(false)
            }
            val ver =
                XGridBuilder(this@CommentDetailActivity).setSpacing(3f)//这几个Spacing的优先级可看XGridBuilder说明
                    //这几个color和drawable的优先级可看XGridBuilder说明
                    .setColor(Color.BLUE)
                    //可设置颜色和drawable,drawable>color
                    .setHLineColor(Color.WHITE)
                    .setVLineColor(Color.WHITE)
                    //是否包括边界
                    .setIncludeEdge(false)
                    //竖直和水平分割线交叉处绘制的是竖直分割线颜色（交叉处属于竖直分割线）
                    .setVerticalIncludeEdge(true)
            rvList2.addItemDecoration(ver.build())
            val drawable = resources.getDrawable(R.drawable.ic_zan)
            if(is_zan=="1"){
                //点赞了
                drawable.setTint(resources.getColor(R.color.colorPrimaryDark))

                tv_dianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
            }else{
                //为点赞
                drawable.setTint(Color.BLACK)

                tv_dianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
            }
            tv_dianzan.setOnClickListener {
                GameImpl.pingLunZan(id){

                    if(is_zan=="1"){
                        val i = zan.toInt() - 1
                        zan = i.toString()
                        is_zan ="0"
                    }else{
                        val i =zan.toInt() + 1
                        zan = i.toString()
                        is_zan ="1"

                    }
                    tv_dianzan.text = zan
                    if(is_zan=="1"){
                        //点赞了
                        drawable.setTint(resources.getColor(R.color.colorPrimaryDark))

                        tv_dianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
                    }else{
                        //为点赞
                        drawable.setTint(Color.BLACK)
                        tv_dianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
                    }
                }

            }
            if(!video.isNullOrEmpty()){
                rvList2.setHeight(dip(160))
                val bannerLayoutManager = object : GridLayoutManager(this@CommentDetailActivity, 1){
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }
                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }
                rvList2.setVisibility(true)
                var list = arrayListOf<String>()
                if(images==null||images.size==0){
                    list.add(String())
                }else{
                    list =  images
                }
                rvList2.layoutManager = bannerLayoutManager
                val gameDetailBannerAdapter = GameDetailBannerAdapter(R.layout.game_detail_banner_item1, list, video)
                rvList2.adapter = gameDetailBannerAdapter

                gameDetailBannerAdapter.setOnItemClickListener { adapter, view, position ->
                    reviewImages(images, position)
                }
            } else if(images!=null&& images.size>0&& images[0] != "http:"&& images[0] != ""){

                val bannerLayoutManager = object : GridLayoutManager(this@CommentDetailActivity, 6){
                }
                val value = object : GridLayoutManager.SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
                        return when (images.size) {
                            1 ->6
                            2 ->3
                            else -> 2
                        }
                    }
                }

                bannerLayoutManager.spanSizeLookup =value
                rvList2.setVisibility(true)
                rvList2.layoutManager = bannerLayoutManager
                val gameDetailBannerAdapter = GameDetailBannerAdapter(R.layout.game_detail_banner_item1, images,video,false)
                rvList2.adapter = gameDetailBannerAdapter
                if(images!=null &&images?.size==1){
                    rvList2.setHeight(dip(125))
                }else
                    if(images!=null &&images?.size==2){
                        rvList2.setHeight(dip(95))
                    }else{
                        if(images?.size!!%3==0){
                            rvList2.setHeight(dip(95)*(images?.size!!/3))
                        }else{
                            rvList2.setHeight(dip(95)*(images?.size!!/3)+1)
                        }
                    }
                gameDetailBannerAdapter.setOnItemClickListener { adapter, view, position ->
                    reviewImages(images, position)
                }
            } else{
                rvList2.setVisibility(false)
            }
//            var list = arrayListOf<String>()
//            if(images==null&&!video.isNullOrEmpty()){
//                list.add(String())
//            }else{
//                list =  images
//            }
        }

        rvList1.layoutManager = object : LinearLayoutManager(this, RecyclerView.VERTICAL,false){        }

    }
    fun initData(){
        if (pinglun2 ==null){
            return
        }else{


        id =pinglun2!!.id
        pid = pinglun2!!.gid
        GameImpl. getChildPingLun(pid,id){
            this?.let {
                list = it
                pinglunAdapter = PinglunAdapter(list[0].son_list)
                val inflate = LayoutInflater.from(this@CommentDetailActivity).inflate(R.layout.empty, null)
                val tv1 = inflate.findViewById<TextView>(R.id.tv1)
                tv1.text = "暂无评论"
                pinglunAdapter.setEmptyView(inflate)
                rvList1.adapter =pinglunAdapter
                pinglunAdapter.setNewInstance(list[0].son_list)
                pinglunAdapter.setOnItemLongClickListener { adapter, view, position ->

                    showDynamicDiscussAddDialog {
                        GameImpl.dellPingLun(list[0].son_list[position].id){
                            if(this){
                                initData()
                            }
                        }
                    }

                    true
                }
            }
        }
        }
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    override fun onBackPressed() {
        if(GSYVideoManager.isFullState(this)){
            GSYVideoManager.backFromWindowFull(this)
        }else{
            finish()
        }

    }

    inner class PinglunAdapter(var lb: ArrayList<Pinglun.PingLunSon>?):BaseQuickAdapter<Pinglun.PingLunSon, BaseDataBindingHolder<ItemDynamicDiscuss1Binding>>
        (R.layout
        .item_dynamic_discuss1,lb) {
        override fun convert(holder: BaseDataBindingHolder<ItemDynamicDiscuss1Binding>, item: Pinglun.PingLunSon) {
            holder.dataBinding?.apply {
                data = item
                if(item.color.isNullOrEmpty()){
                    tvName.setTextSize(14f)
                    tvName .setHasColors(false,null)
                    tvName.setText(item.user_name)
                }else{
                    if(item.color.size == 1){
                        tvName.setTextSize(14f)
                        tvName.setText(item.user_name)
                        tvName .setHasColors(false,null)
                        tvName.setTextColor(Color.parseColor(item.color[0]))
                    }else{
                        var intArray = IntArray(item.color!!.size)
                        item.color?.forEachIndexed { index, s ->
                            intArray[index] = Color.parseColor(s)
                        }
                        tvName.setTextSize(14f)
                        tvName.setTextColor(Color.parseColor(item.color[0]))
                        tvName.setText(item.user_name)
                        tvName .setHasColors(true,intArray)
                    }
                }
                var pinglun :String = if (TextUtils.isEmpty(item.beihuifu_user_name)|| TextUtils.equals("null",item.beihuifu_user_name)){
                    "${item.content}"
                }else{
                    "回复@${item.beihuifu_user_name}:${item.content}"
                }
                val spannableString1 = SpannableStringBuilder(pinglun)
                val span1: ClickableSpan = object : ClickableSpan() {
                    override fun onClick(widget: View) {
//                        GameCommentActivity.start(context as Activity, SpConsts.gid,item.id ,ppid,1,pinglun1)
                    }

                    override fun updateDrawState(ds: TextPaint) {
                        ds.color = context.resources.getColor(R.color.colorPrimaryDark)
                        ds.isFakeBoldText = true
                        ds.isUnderlineText = false
                    }
                }
                if (TextUtils.isEmpty(item.beihuifu_user_name)|| TextUtils.equals("null",item.beihuifu_user_name)){

                }else{
                    spannableString1.setSpan(span1, 2, 2+item.beihuifu_user_name.length+1, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
                }
                val view = holder.getView<TextView>(R.id.tvContent)
                view.text=spannableString1
                view.movementMethod = LinkMovementMethod.getInstance()
                tvContent.setOnClickListener {
                    if(startLogin()) {
                        showSendMessageDialog("回复@${item.user_name}") {
                            GameImpl.pushPingLun(
                                this@CommentDetailActivity,
                                gid,
                                null,
                                null,
                                this,
                                "",
                                item.id,
                                pinglun2!!.id,
                                2,
                                null
                            ) {
                                if (this) {
                                    initData()
                                }
                            }
                        }
                    }
                }
                if(!item.point.isNullOrEmpty()) {
                    rbStar.setVisibility(true)
                    rbStar.rating = item.point.toFloat()
                }else{
                    rbStar.setVisibility(false)
                }
                rvPingLun.setVisibility(false)

                tvPingLunAll.setVisibility(false)
                tvPinglun .setVisibility(false)
                val drawable = resources.getDrawable(R.drawable.ic_zan)
                if(item.is_zan=="1"){
                    //点赞了
                    drawable.setTint(resources.getColor(R.color.colorPrimaryDark))
                    tvDianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
                }else{
                    //为点赞
                    drawable.setTint(Color.BLACK)
                    tvDianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
                }
                rbStar.setVisibility(false)
                tvDianzan.setOnClickListener {
                    GameImpl.pingLunZan(item.id){
                        if(item.is_zan=="1"){
                            val i = item.zan.toInt() - 1
                            item.zan = i.toString()
                            item.is_zan ="0"
                        }else{
                            val i = item.zan.toInt() + 1
                            item.zan = i.toString()
                            item.is_zan ="1"
                        }
                        notifyItemChanged(holder.position)
                    }
                }
            }
        }
    }
}